<template>
  <el-dialog :visible.sync="visible" :title="!dataForm.permId ? '新增' : '修改'" :close-on-click-modal="false"
    :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm"  @keydown.enter.native.prevent="dataFormSubmitHandle()"
      label-width="120px">
      <el-form-item prop="bton" label="菜单类型" size="mini">
        <el-radio-group v-model="dataForm.bton" :disabled="!!dataForm.permId">
          <el-radio :label=0>菜单</el-radio>
          <!-- :label->是绑定值 前面必须要有: -->
          <el-radio :label=1>按钮</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="permsName" label="名称">
        <el-input v-model="dataForm.permsName" placeholder="名称"></el-input>
      </el-form-item>
      <el-form-item prop="parentName" label="上级菜单" class="menu-list">
        <el-popover v-model="menuListVisible" ref="menuListPopover" placement="right-end" trigger="click">
          <el-tree 
            :data="menuList" 
            :props="{ label: 'permsName', children: 'children' }" 
            node-key="permId" 
            ref="menuListTree"
            :highlight-current="true" 
            :expand-on-click-node="false" 
            accordion
            @current-change="menuListTreeCurrentChangeHandle">
          </el-tree>
        </el-popover>
        <el-input v-model="dataForm.parentName" v-popover:menuListPopover :readonly="true"
          placeholder="上级菜单">
          <i v-if="dataForm.parentId !== 0" slot="suffix" @click.stop="deptListTreeSetDefaultHandle()"
            class="el-icon-circle-close el-input__icon"></i>
        </el-input>
      </el-form-item>
      <el-form-item  prop="path" label="路由">
        <el-input v-model="dataForm.path" placeholder="路由"></el-input>
      </el-form-item>
      <!-- <el-form-item prop="sort" label="排序">
        <el-input-number v-model="dataForm.sort" controls-position="right" :min="0"
          label="排序"></el-input-number>
      </el-form-item> -->
      <el-form-item prop="perms" label="授权标识">
        <el-input v-model="dataForm.perms" placeholder="多个用逗号分隔, 如: user:list,user:create"></el-input>
      </el-form-item>
      <el-form-item v-if="(dataForm.bton === 0)" prop="icon" label="菜单图标" class="icon-list">
        <el-popover v-model="iconListVisible" ref="iconListPopover" placement="bottom-start" trigger="click"
          popper-class="mod-sys__menu-icon-popover">
          <div class="mod-sys__menu-icon-inner">
            <div class="mod-sys__menu-icon-list">
              <el-button v-for="(item, index) in iconList" :key="index" @click="iconListCurrentChangeHandle(item)"
                :class="{ 'is-active': dataForm.icon === item }">
                <svg class="icon-svg" aria-hidden="true">
                  <use :xlink:href="`#${item}`"></use>
                </svg>
              </el-button>
            </div>
          </div>
        </el-popover>
        <el-input v-model="dataForm.icon" v-popover:iconListPopover :readonly="true"
          placeholder="菜单图标"></el-input>
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">确定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import debounce from 'lodash/debounce'
import { getIconList } from '@/utils'
import servicesApi from '@/services/servicesApi'
export default {
  data() {
    return {
      visible: false,
      menuList: [],
      menuListVisible: false,
      iconList: [],
      iconListVisible: false,
      dataForm: {
        permId: '',
        bton: 0,
        permsName: '',
        parentId: 3,
        parentName: '',
        path: '',
        perms: '',
        sort: 0,
        icon: ''
      }
    }
  },
  computed: {
    dataRule() {
      return {
        permsName: [
          { required: true, message: '必填项不能为空', trigger: 'blur' }
        ],
        parentName: [
          { required: true, message: '必填项不能为空', trigger: 'change' }
        ]
      }
    }
  },
  watch: {
    'dataForm.bton'(val) {
      this.$nextTick(() => {
        //  延时到下一帧才开始，也就是页面刚刚渲染结束！！
        this.$refs['dataForm'].clearValidate()
      })
      
    }
  },
  methods: {
    init(permId) {
      this.dataForm.permId = permId || 0
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        this.iconList = getIconList()
        // this.dataForm.parentName = '根菜单'
        this.getMenuList().then(() => {
          if (this.dataForm.permId) { //修改
            // console.log('修改菜单')
            this.getInfo()
          } else {
            // console.log('新增菜单')
            this.deptListTreeSetDefaultHandle()
          }
        })
      })
    },
    // 获取菜单列表
    getMenuList() {
      return servicesApi.getMenuList().then(res => {
        if (res.data.code !== 200) {
          return this.$message.error(res.data.msg)
        }
        this.menuList = res.data.data
      }).catch(() => { })
      // return this.$http.get('/sys/menu/list?type=0').then(({ data: res }) => {
      //   if (res.code !== 0) {
      //     return this.$message.error(res.msg)
      //   }
      //   this.menuList = res.data
      // }).catch(() => { })
    },
    // 获取信息
    getInfo() {
      servicesApi.getMenuById(this.dataForm.permId).then(res => {
        if (res.data.code !== 200) {
          return this.$message.error(res.data.msg)
        }
        this.dataForm = {
          ...this.dataForm,
          ...res.data.data
        }
        if (this.dataForm.parentId === 3) {
          // console.log('设置默认上级菜单')
          return this.deptListTreeSetDefaultHandle()
        }
        // // console.log('设置上级菜单%o', this.dataForm)
        this.$refs.menuListTree.setCurrentKey(this.dataForm.parentId)
        this.menuListTreeSetParent(this.dataForm)
      }).catch(() => { })
      // this.$http.get(`/sys/menu/${this.dataForm.permId}`).then(({ data: res }) => {
      //   if (res.code !== 0) {
      //     return this.$message.error(res.msg)
      //   }
      //   this.dataForm = {
      //     ...this.dataForm,
      //     ...res.data
      //   }
      //   if (this.dataForm.parentId === '0') {
      //     return this.deptListTreeSetDefaultHandle()
      //   }
      //   this.$refs.menuListTree.setCurrentKey(this.dataForm.parentId)
      // }).catch(() => { })
    },
    // 上级菜单树, 设置默认值
    deptListTreeSetDefaultHandle() {
      this.dataForm.parentId = 3
      this.dataForm.parentName = '根菜单'
    },
    menuListTreeSetParent(data) {
      // // console.log(data)
      let parentName = this.$refs.menuListTree.getNode(data.parentId).data.permsName
      // console.log(parentName)
      this.dataForm.parentName = parentName
      // console.log('选中的Pid=%s', this.dataForm.parentId);
      this.menuListVisible = false
    },
    // 上级菜单树, 选中
    menuListTreeCurrentChangeHandle(data) {
      // // console.log(data)
      this.dataForm.parentId = data.permId
      // let parentName = this.$refs.menuListTree.getNode(data.permId).data.permsName
      // // console.log(parentName)
      // this.dataForm.parentName = 'parentName'
      this.dataForm.parentName = data.permsName
      // console.log('选中的Pid=%s', this.dataForm.parentId);

      this.menuListVisible = false
    },
    // 图标, 选中
    iconListCurrentChangeHandle(icon) {
      this.dataForm.icon = icon
      this.iconListVisible = false
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function() {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        if (this.dataForm.permId) { // 修改
          // console.log('修改菜单')
          servicesApi.updateMenu(this.dataForm).then(res => {
            if (res.data.code !== 200) {
              return this.$message.error(res.data.msg)
            }
            this.$message({
              message: '修改成功',
              type: 'success',
              duration: 500,
              onClose: () => {
                this.visible = false
                this.$emit('refreshDataList')
              }
            })
          })
        } else {  // 新增
          // console.log('新增菜单')
          servicesApi.addMenu(this.dataForm).then(res => {
            if (res.data.code !== 200) {
              return this.$message.error(res.data.msg)
            }
            this.$message({
              message: '添加成功',
              type: 'success',
              duration: 500,
              onClose: () => {
                this.visible = false
                this.$emit('refreshDataList')
              }
            })
          })
        }
        // this.$http[!this.dataForm.permId ? 'post' : 'put']('/sys/menu', this.dataForm).then(({ data: res }) => {
        //   if (res.code !== 0) {
        //     return this.$message.error(res.msg)
        //   }
        //   this.$message({
        //     message: this.$t('prompt.success'),
        //     type: 'success',
        //     duration: 500,
        //     onClose: () => {
        //       this.visible = false
        //       this.$emit('refreshDataList')
        //     }
        //   })
        // }).catch(() => { })
      })
    }, 1000, { 'leading': true, 'trailing': false })
  }
}
</script>

<style lang="scss">
.mod-sys__menu {

  .menu-list,
  .icon-list {

    .el-input__inner,
    .el-input__suffix {
      cursor: pointer;
    }
  }

  &-icon-popover {
    width: 458px;
    overflow: hidden;
  }

  &-icon-inner {
    width: 478px;
    max-height: 258px;
    overflow-x: hidden;
    overflow-y: auto;
  }

  &-icon-list {
    width: 458px;
    padding: 0;
    margin: -8px 0 0 -8px;

    >.el-button {
      padding: 8px;
      margin: 8px 0 0 8px;

      >span {
        display: inline-block;
        vertical-align: middle;
        width: 18px;
        height: 18px;
        font-size: 18px;
      }
    }
  }
}
</style>
